package com.theaf.basemodule.service.other;

import com.theaf.core.utils.DictionaryHelper;
import com.theaf.core.utils.HttpHelper;
import com.theaf.core.utils.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 微信服务
 * @author Administrator
 *
 */
@Component
public class WeixinService{
	@Autowired
	private RedisTemplate redisTemplate ;
	/**
	 * 微信企业ID
	 */
	@Value("${smyw.wx.corpid}")
	private String CORPID="wx49172e12ac5c6b01";

	
	/*
	 * 通过微信企业号发送信息
	 * appid 应用
	 * toUser：UserID列表（消息接收者，多个接收者用‘|’分隔），可以为空。特殊情况：指定为@all，则向关注该企业应用的全部成员发送
	 * toParty：PartyID列表，多个接受者用‘|’分隔，可以为空。当touser为@all时忽略本参数 
	 * toTag：标签列表，多个接受者用‘|’分隔，可以为空。当touser为@all时忽略本参数 
	 * agentId：企业应用的id，默认为1
	 */	
	public void sendMessage(String toUser,String toParty,String toTag,String content,String agentId) throws Exception{
		if(agentId==null){
			agentId = "1";
		}
		String accessToken = getAccessToken(agentId);
		String path = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken;
		Map param = new HashMap();
		if(toUser!=null) {
			param.put("touser", toUser);
		}
		if(toParty!=null) {
			param.put("toparty", toParty);
		}
		if(toTag!=null) {
			param.put("totag", toTag);
		}
		param.put("msgtype", "text");
		param.put("agentid", agentId==null?"1":agentId);
		Map contentMap = new HashMap();
		contentMap.put("content", content);
		param.put("text", contentMap);
		param.put("safe", "0");
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,param), Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
	}
	/**
	 * 创建微信成员
	 * @param phone
	 * @param mail
	 * @param userName
	 * @param gender
	 * @param dept
	 * @return
	 * @throws Exception
	 */
	public void createUser(String appId,String userId,String phone,String mail,String userName,Integer gender,int[] dept) throws Exception{
		if(StringUtils.isEmpty(userId)) {
			throw new Exception("用户微信成员账号不能为空！");
		}
		String path = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token="+this.getAccessToken(appId);
		Map param = new HashMap();
		param.put("userid", userId);
		if(StringUtils.isNotEmpty(userName)) {
			param.put("name", userName);
		}
		if(StringUtils.isNotEmpty(phone)) {
			param.put("mobile", phone);
		}
		if(StringUtils.isNotEmpty(mail)) {
			param.put("email", mail);
		}
		if(gender!=null) {
			param.put("gender", gender);
		}
		if(dept!=null) {
			param.put("department", dept);
		}
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,param), Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
	}
	/**
	 * 更新用户
	 * @param userId 用户ID
	 * @param phone
	 * @param mail
	 * @param userName
	 * @param gender
	 * @param dept
	 * @throws Exception
	 */
	public void updateUser(String appId,String userId,String phone,String mail,String userName,Integer gender,int[] dept) throws Exception{
		if(StringUtils.isEmpty(userId)) {
			throw new Exception("用户微信成员账号不能为空！");
		}
		String path = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token="+this.getAccessToken(appId);
		Map param = new HashMap();
		param.put("userid", userId);
		if(StringUtils.isNotEmpty(userName)) {
			param.put("name", userName);
		}
		if(StringUtils.isNotEmpty(phone)) {
			param.put("mobile", phone);
		}
		if(StringUtils.isNotEmpty(mail)) {
			param.put("email", mail);
		}
		if(gender!=null) {
			param.put("gender", gender);
		}
		if(dept!=null) {
			param.put("department", dept);
		}
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,param), Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
	}

	/**
	 * 判断用户是否存在
	 * @param appId
	 * @param userId
	 * @return
	 */
	public boolean existUser(String appId,String userId) {
		try{
			findUser(appId,userId);
		}catch(Exception e){
			return false;
		}
		return true;
	}

	/**
	 * 查询用户
	 * @param appId 微信应用id
	 * @param userId 用户Id
	 * @return
	 * @throws Exception
	 */
	public Map findUser(String appId,String userId) throws Exception{
		String path = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="
				+this.getAccessToken(appId)+"&userid="+userId;
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,null), Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
		return maps;
	}

	/**
	 * 查询部门
	 * @param deptId 为空查询所有部门，为1查询顶级部门，其它查询子部门
	 * @return [{
			"id": 2,
			"name": "广州研发中心",
			"parentid": 1,
			"order": 10,
	        "department":[...]
			}...]
	 * @throws Exception
	 */
	public List<Map> findDept(String deptId) throws Exception{
		String path = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="
				+this.getAccessToken("1")+"&id="+deptId;
		ObjectMapper objectMapper = new ObjectMapper();
		String ret = HttpHelper.post(path,null);
		//objectMapper.get
		Map<String, Object> maps = objectMapper.readValue(ret, Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
		return (List<Map>)maps.get("department");
	}

	/**
	 * 查询标签
	 * @return [{
	"tagid": 2,
	"tagname": "广州研发中心"
	}..]
	 * @throws Exception
	 */
	public List<Map> findTag() throws Exception{
		String path = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token="
				+this.getAccessToken("1");
		ObjectMapper objectMapper = new ObjectMapper();
		String ret = HttpHelper.post(path,null);
		//objectMapper.get
		Map<String, Object> maps = objectMapper.readValue(ret, Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
		return (List<Map>)maps.get("taglist");
	}

	/**
	 * 邀请
	 * @param appId 微信应用id
	 * @param users 用户
	 * @param partys 部门
	 * @param tags 标签
	 * @throws Exception
	 */
	public void invite(String appId,String[] users,String[] partys,String[] tags) throws Exception{
		String path ="https://qyapi.weixin.qq.com/cgi-bin/invite/send?access_token="+this.getAccessToken(appId);
		Map submit = new HashMap();
		submit.put("user",users);
		submit.put("party",partys);
		submit.put("tag",tags);
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,submit), Map.class);
		String error = (String)maps.get("errmsg");
		if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
	}
	/**
	 * 删除用户
	 * @param appId 微信应用id
	 * @param userId
	 * @throws Exception
	 */
	public void deleteUser(String appId,String userId) throws Exception{
		String path = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token="+this.getAccessToken(appId)+
				"&userid="+userId;
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,null), Map.class);
        String error = (String)maps.get("errmsg");
        if(((Integer)maps.get("errcode")).intValue()!=0) {
			throw new Exception(error);
		}
	}

	/**
	 * 获取微信凭证
	 * @param appId 微信应用id
	 */
	private String getAccessToken(String appId) throws Exception{
		if(appId==null){
			appId = "1";
		}
		String ret = null;
		String accessToken = (String)redisTemplate.opsForValue().get("WX_ACCESS_TOKEN_"+appId);
		if(accessToken!=null){
			Long last = (Long)redisTemplate.opsForValue().get("WX_TIMESTAMP_"+appId);
			Integer expires = (Integer)redisTemplate.opsForValue().get("WX_EXPIRES_IN_"+appId);
			Long now = (new Date()).getTime();
			Long sub = now - last;
			if(sub>expires*1000){
				accessToken=null;
			}else{
				ret = accessToken;
			}
		}else if(StringUtils.isEmpty(accessToken)){
			String corpid = CORPID;
			String appsecret= DictionaryHelper.getChlidMemo("WX_SECRECT",appId);
			String path ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+appsecret;
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> maps = objectMapper.readValue(HttpHelper.post(path,null), Map.class);
			String error = (String)maps.get("errmsg");
			if(((Integer)maps.get("errcode")).intValue()!=0) {
				throw new Exception(error);
			}
			Set<String> key = maps.keySet();
			Iterator<String> iter = key.iterator();
			while (iter.hasNext()) {
	        	 String field = iter.next();
	        	 if("access_token".equals(field)){
	        		ret = (String)maps.get(field);
					 redisTemplate.opsForValue().set("WX_ACCESS_TOKEN_"+appId,  ret);
					 redisTemplate.opsForValue().set("WX_EXPIRES_IN_"+appId, maps.get("expires_in"));
					 redisTemplate.opsForValue().set("WX_TIMESTAMP_"+appId, System.currentTimeMillis()+"");
	        	 }
	        }
		}
		return ret;
	}
}
